package com.itheima.factory;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import com.itheima.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 用于创建service代理对象的工厂
 */
public class beanfactory {
    //把这个accountService作为set方法用于spring的注入，然后在代理方法（invoke）中进行使用，需要把set方法改成final。
    private IAccountService accountService;

    private TransactionManager transactionManager;
    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    public final void setAccountService(IAccountService accountService) {
        this.accountService = accountService;
    }
    public IAccountService getAccountService() {
        return accountService;
    }
    /**
     * 获取service的代理对象
     */
    public IAccountService getAccountServie(){
        return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            /**
             * 添加事务的支持
             * @param proxy
             * @param method
             * @param args
             * @return
             * @throws Throwable
             */
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object returnvalue=null;
                //事务改造代理
                try{
                    //开启事务
                    transactionManager.beginTransaction();
                    //执行操作
                    //List<Account> accounts= accountDao.findAllAccount();
                    returnvalue= method.invoke(accountService,args);
                    //提交事务
                    transactionManager.commitTransaction();
                    //返回结果
                    return returnvalue;
                }catch (Exception e){
                    //回滚操作
                    transactionManager.rollbackTransaction();
                    throw new RuntimeException(e);
                }finally {
                    //释放连接
                    transactionManager.closeTransaction();
                }
            }
        });

    }

}
